package AudioTool;



import java.io.File;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineEvent;
import javax.sound.sampled.LineListener;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author yk
 */
public class ClipPlayer implements LineListener{
   private AudioInputStream soundStream;
   private Clip clip;
   private File soundFile;
   private boolean replay=false;
  
   public  ClipPlayer(File audioFile)
   {
     soundFile=audioFile;
     openFile();
   }
   public boolean openFile()
   {
      try
      {
        soundStream=AudioSystem.getAudioInputStream(soundFile);
      }catch(Exception e){
        e.printStackTrace();
        return false;
      }
      return loadClip();
   }
   public boolean loadClip()
   {
      try
      {
          AudioFormat audioFormat=soundStream.getFormat();
        //  DataLine.Info dataLineInfo=new DataLine.Info(Clip.class,audioFormat);
          DataLine.Info dataLineInfo=new DataLine.Info(Clip.class,AudioSystem.getTargetFormats(AudioFormat.Encoding.PCM_SIGNED,audioFormat),(int)audioFormat.getFrameRate(),(int)audioFormat.getFrameRate()*2);
              if(!AudioSystem.isLineSupported(dataLineInfo)){System.err.print("Unsuported Clip file");
              return false;
              }
              clip=(Clip)AudioSystem.getLine(dataLineInfo);
           
              clip.addLineListener(this);
              clip.open(soundStream);
      }catch(Exception e)
                  {
                  e.printStackTrace();
                  return false;
                  }
                  return true;
      
      
   }
   public void play()
   {
      clip.start();
   }
   
   public void setreplay(boolean a){replay=a;}
   public void close()
   {
      if(clip!=null){clip.stop();clip.close();}
   }
    public void update(LineEvent e) {
       if(e.getType()==LineEvent.Type.STOP&&!replay)
                 close();
       else if(e.getType()==LineEvent.Type.STOP&&replay)
       {
          System.out.println("replay");
          clip.loop(Clip.LOOP_CONTINUOUSLY);
       }
    }
  
}
